/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable no-shadow */
/* eslint-disable react/no-array-index-key */
/**
 * 面试详情-卡片
 */
import React, { useRef, useEffect } from 'react';
import { Divider, Icon, Button, List } from 'antd';
import BizIcon from '@/components/BizIcon';
import moment from 'moment';
import { getDisplayText } from '@/utils/dataDictUtil';
import { useInterviewRoundList } from '../../hooks';
import { PreviewModal, DetailItem, Operates, FileShowView } from '../../components';
import { getFileType } from '../../../EntryManage/utils';
import styles from './index.less';
import { INTERVIEW_WAY, CONTACT_RESULT, CONTACT_WAY, INTERVIEW_STATUS, NOTICE_TYPE } from '../../dictionary';
import {
    InterviewEditOperate,
    InterviewNoticeOperate,
    InterviewDetailOperate,
    InterviewSummaryOperate,
    InterviewStartOperate,
    InterviewPreparationOperate,
    InterviewEditPreparationOperate,
    InterviewCopyOperate
} from '../index';

const emptyStr = '--';

export default function InterviewCard({ candidateId, data = {}, interviewerFlag, principalFlag, launcherFlag }) {
    const [expand, setExpand] = React.useState(false);
    const handleToggleExpand = e => {
        e.preventDefault();
        setExpand(val => !val);
    };
    const [showFileList, setShowFileList] = React.useState([]);
    const [deadline, setDeadline] = React.useState('');
    const [topicInfo, setTopicInfo] = React.useState('');
    const previewRef = useRef();
    // 面试轮次
    const { data: interviewRoundList } = useInterviewRoundList();

    const {
        recruitInterviewHomeworkVO = {}, // 面试题目
        arrangeDetailVO = {},
        contactRecordDetailVO = {},
        currentEmployeeInterviewPrepareFlag, // 当前员工是否有面试准备 有面试准备后才可以开始面试
        currentEmployeeInterviewRecordFlag, // 当前员工是否有面试记录
        candidateInterviewRecordFlag, // 是否有面试记录  有面试记录才可以查看面试详情
        interviewPrepareFlag, // 是否有面试准备
        candidateLink
    } = data;
    const {
        id: arrangeId,
        interviewWay,
        interviewStartTime,
        interviewEndTime,
        interviewRoundName,
        interviewLocation = emptyStr,
        interviewEmployees = [],
        interviewStatus,
        reason = '' // 拒绝原因
    } = arrangeDetailVO;

    useEffect(() => {
        if (recruitInterviewHomeworkVO) {
            const { topicFileUrl, deadline, topicInfo } = recruitInterviewHomeworkVO;
            setDeadline(deadline);
            setTopicInfo(topicInfo);
            if (topicFileUrl) {
                const fileArray = JSON.parse(topicFileUrl);
                setShowFileList(
                    fileArray.map(item => ({
                        uid: item.id,
                        name: item.name,
                        status: 'done',
                        url: item.url,
                        response: item.url
                    }))
                );
            }
        }
    }, [recruitInterviewHomeworkVO]);

    const {
        id: contactId,
        contractEmployeeName,
        contractEmployeePost,
        contactDesc = emptyStr,
        contactResult,
        contactTime,
        contactWay
    } = contactRecordDetailVO;
    const getDisplay = (dict, val) => {
        if (!val) {
            return emptyStr;
        }
        return getDisplayText(dict, val);
    };

    const renderWorkTitle = () => {
        if (!deadline) {
            return emptyStr;
        }
        const mapping = ['日', '一', '二', '三', '四', '五', '六'];
        const m = moment(deadline);
        return `星期${mapping[m.day()]} ${m
            .format('MM月DD日')
            .split('月')
            .map(item => (item.startsWith('0') ? item.substr(1) : item))
            .join('月')} · ${interviewRoundName}`;
    };

    const renderTitle = () => {
        if (!interviewStartTime) {
            return emptyStr;
        }
        const mapping = ['日', '一', '二', '三', '四', '五', '六'];
        const m = moment(interviewStartTime);
        return `星期${mapping[m.day()]} ${m
            .format('MM月DD日')
            .split('月')
            .map(item => (item.startsWith('0') ? item.substr(1) : item))
            .join('月')} · ${interviewRoundName}`;
    };
    // 面试时间区间
    const renderTimeRegion = () => {
        if (!interviewStartTime || !interviewEndTime) {
            return emptyStr;
        }
        return `${moment(interviewStartTime).format('YYYY-MM-DD HH:mm')}~${moment(interviewEndTime).format('HH:mm')}`;
    };
    // 面试官
    const renderInterviewEmployee = () => {
        if (!interviewEmployees.length) {
            return emptyStr;
        }
        const split = '、';
        return interviewEmployees.map(item => item.employeeName).join(split);
    };

    // 联系人
    const renderContact = () => {
        if (!contractEmployeeName || !contractEmployeePost) {
            return emptyStr;
        }
        return `${contractEmployeeName} ${contractEmployeePost}`;
    };
    // 预览文件
    const handlePreview = source => {
        const { id, url, name } = source;
        const fileType = getFileType(name);
        previewRef.current.open({
            type: fileType,
            title: id,
            origin: url,
            encode: fileType === 'office',
            originName: name
        });
    };
    // 联系时间
    const renderContactTime = () => {
        if (!contactTime) {
            return emptyStr;
        }
        return moment(contactTime).format('YYYY-MM-DD HH:mm');
    };
    const renderFooter = () => {
        // 招聘负责人通知候选人
        const notice = noticeType =>
            principalFlag && (
                <InterviewNoticeOperate candidateId={candidateId} noticeType={noticeType} contactId={contactId} />
            );
        // 招聘负责人修改面试
        const edit = principalFlag && <InterviewEditOperate candidateId={candidateId} contactId={contactId} />;
        // 查看面试详情
        const detail = !!candidateInterviewRecordFlag && (
            <InterviewDetailOperate arrangeId={arrangeId} candidateId={candidateId} />
        );
        const copy = <InterviewCopyOperate candidateLink={candidateLink} />;
        // 招聘负责人和招聘发起人查看面试总结
        const summary = (principalFlag || launcherFlag) && (
            <InterviewSummaryOperate candidateId={candidateId} arrangeId={arrangeId} />
        );

        const renderStart = show =>
            interviewerFlag && show && <InterviewStartOperate candidateId={candidateId} arrangeId={arrangeId} />;
        const preparation = currentEmployeeInterviewPrepareFlag
            ? interviewerFlag && <InterviewEditPreparationOperate candidateId={candidateId} arrangeId={arrangeId} />
            : interviewerFlag && <InterviewPreparationOperate candidateId={candidateId} arrangeId={arrangeId} />;
        // 1=待接受 2=待面试 3=待总结 4=通过 5=淘汰 6=需复试 7=已取消
        let arr = [
            [],
            [edit, notice(NOTICE_TYPE.INVITE), copy],
            [renderStart(!!interviewPrepareFlag), preparation, edit, notice(NOTICE_TYPE.INVITE), copy],
            [renderStart(!currentEmployeeInterviewRecordFlag), summary, detail, copy],
            [detail, copy],
            [notice(NOTICE_TYPE.WEED_OUT), detail, copy],
            [detail, copy],
            [detail, copy]
        ];
        const item = INTERVIEW_STATUS.find(_ => _.value === interviewStatus) || {};

        // 如果是面试作业方式

        if (interviewWay === 5) {
            arr = [
                [],
                [edit, notice(NOTICE_TYPE.INVITE), copy],
                [notice(NOTICE_TYPE.INVITE), edit, copy],
                [summary, detail, copy],
                [detail, copy, copy],
                [notice(NOTICE_TYPE.WEED_OUT), detail, copy],
                [detail, copy],
                [detail, copy]
            ];
        }

        const operates = arr[interviewStatus] || [];
        return (
            <div className={styles.footer} style={{ background: item.background }}>
                <span className={styles.status} style={{ color: item.color }}>
                    {item.text} {reason && `（${reason}）`}
                </span>
                <div>
                    <Operates operates={operates} />
                </div>
            </div>
        );
    };
    return (
        <div className={styles.wrapper}>
            <div className={styles.title}>{interviewWay === 5 ? renderWorkTitle() : renderTitle()}</div>
            <div className={styles.content}>
                <div>
                    {interviewWay === 5 && (
                        <>
                            <DetailItem label="面试题目">
                                <div className={styles.topicDiv}>
                                    <div className={styles.topicInfo}>{topicInfo}</div>
                                    {showFileList.length > 0 && (
                                        <div className={styles.fileInfo}>
                                            <List
                                                split={false}
                                                itemLayout="horizontal"
                                                dataSource={showFileList}
                                                renderItem={item => (
                                                    <List.Item key={item.uid}>
                                                        <FileShowView
                                                            handlePreview={handlePreview}
                                                            item={item}
                                                            showPreview
                                                            showDownLoad
                                                        ></FileShowView>
                                                    </List.Item>
                                                )}
                                            />
                                        </div>
                                    )}
                                </div>
                            </DetailItem>
                            <div className={styles.vSplit}></div>
                            <DetailItem label="截止日期">
                                <div className={styles.topicInfo}>{deadline}</div>
                            </DetailItem>
                        </>
                    )}

                    {interviewWay !== 1 && interviewWay !== 5 && (
                        <DetailItem label="面试方式">
                            <div className={styles.topicInfo}>{getDisplayText(INTERVIEW_WAY, interviewWay)}</div>
                        </DetailItem>
                    )}
                    {interviewWay === 1 && (
                        <DetailItem label="面试地点">
                            <div className={styles.topicInfo}>{interviewLocation}</div>
                        </DetailItem>
                    )}
                    <div className={styles.vSplit}></div>
                    {interviewWay !== 5 && (
                        <DetailItem label="面试时间">
                            <div className={styles.topicInfo}>{renderTimeRegion()}</div>
                        </DetailItem>
                    )}
                    <div className={styles.vSplit}></div>
                    <DetailItem label="面试官">
                        <div className={styles.topicInfo}>{renderInterviewEmployee()}</div>
                    </DetailItem>
                </div>
                <Divider style={{ margin: '19px 0' }}></Divider>
                <div>
                    {expand && (
                        <>
                            <div className={styles.box}>
                                <DetailItem style={{ flex: 1 }} label="联系人">
                                    <div className={styles.topicInfo}> {renderContact()}</div>
                                </DetailItem>
                                <DetailItem style={{ flex: 1 }} label="联系方式">
                                    <div className={styles.topicInfo}> {getDisplay(CONTACT_WAY, contactWay)}</div>
                                </DetailItem>
                                <a href="#" className={styles.action} onClick={handleToggleExpand}>
                                    收起
                                    <BizIcon type="fold_arrow_o" />
                                </a>
                            </div>
                            <div className={styles.vSplit}></div>
                            <div className={styles.box}>
                                <DetailItem style={{ flex: 1 }} label="联系时间">
                                    <div className={styles.topicInfo}> {renderContactTime()}</div>
                                </DetailItem>
                                <DetailItem style={{ flex: 1 }} label="联系结果">
                                    <div className={styles.topicInfo}> {getDisplay(CONTACT_RESULT, contactResult)}</div>
                                </DetailItem>
                                <div className={styles.action}></div>
                            </div>
                            <div className={styles.vSplit}></div>
                        </>
                    )}
                    <div className={styles.box}>
                        <DetailItem style={{ flex: 1 }} label="联系内容">
                            <div className={styles.topicInfo}> {contactDesc}</div>
                        </DetailItem>
                        {!expand && (
                            <a href="#" className={styles.action} onClick={handleToggleExpand}>
                                查看更多
                                <BizIcon type="unfold_arrow_o" />
                            </a>
                        )}
                    </div>
                </div>
            </div>
            <PreviewModal title ref={previewRef} height="650px" />
            {renderFooter()}
        </div>
    );
}
